import json

from readyaml import ReadYamlData, get_testcase_yaml
from debugtalk import DebugTalk


class BaseRequest:
    def __init__(self):
        self.read = ReadYamlData()

    def replace_load(self, data):
        """
        yaml 文件替换解析有 ${}格式的数据
        :return:
        """
        str_data = data
        if not isinstance(data, str):
            str_data = json.dumps(data, ensure_ascii=False)
            print(f'str_data的值是：{str_data}')

        for i in range(str_data.count('${')):
            # print(i)
            if "${" in str_data and "}" in str_data:
                # TODO index检测字符串是否 子字符串，并找到字符串的索引位置
                start_index = str_data.index('$')
                end_index = str_data.index('}', start_index) + 1
                print('索引---------------------------------------：', start_index, end_index)
                ref_all_params = str_data[start_index:end_index]
                print('ref_all_params=======================================', ref_all_params)

                # 取出函数名
                func_name = ref_all_params[2:ref_all_params.index('(')]
                print('func_name=======', func_name)

                # 取出函数的参数值
                func_params = ref_all_params[ref_all_params.index('(') + 1:ref_all_params.index(')')]
                print(func_params)

                print('yaml文件替换解析前====', str_data)
                # TODO 传入替换的参数获取对应的值（反射） 通过反射（拿到对象然后输入方法进行调用）
                extract_data = getattr(DebugTalk(), func_name)(*func_params.split(',') if func_params else "")
                print('yaml文件替换解析后========', extract_data)
                str_data = str_data.replace(ref_all_params, str(extract_data))
                print(str_data)

        # TODO 还原数据
        if data and isinstance(data, dict):
            data = json.loads(str_data)
        else:
            data = str_data

        return data


if __name__ == '__main__':
    data = get_testcase_yaml('../testcase/Login/login.yaml')[0]
    print(data)
    print(type(data))
    base = BaseRequest()
    res = base.replace_load(data)
    print("res==============",res)
